<template>
  <!-- 单位余额统计 -->
  <div class="swipe_details">
    <el-form :inline="true" :model="elform" size="mini">
      <el-form-item class="searchmarigin">
        <el-button type="primary" @click="onSubmit" size="mini" icon="el-icon-search">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onExport" size="mini" icon="el-icon-document-copy">导出</el-button>
      </el-form-item>
      <el-form-item>
        <el-popover width="600" placement="top" trigger="click">
          <el-row>
            <el-col :span="6" v-for="item in Object.keys(formThead)" :key="item">
              <el-checkbox
                :label="formThead[item].label"
                v-model="formThead[item].checked"
                @change="getHeaderDate()"
              ></el-checkbox>
            </el-col>
          </el-row>
          <el-button slot="reference" size="mini" type="primary" icon="el-icon-edit-outline">自定义</el-button>
        </el-popover>
      </el-form-item>
    </el-form>
    <div class="tablemain">
      <el-table
        v-loading="loading"
        :data="detailslist"
        ref="table"
        border
        highlight-current-row
        style="width: 100%"
        :header-cell-style="headFirst"
        :cell-style="
          detailsTotal ? (res) => headFirst_col(res, detailslist) : () => {}
        "
      >
        <el-table-column
          prop="unitName"
          label="单位名称"
          v-if="formThead.unitName.checked"
          min-width="120px"
        ></el-table-column>
     
         <el-table-column
          prop="userCount"
          label="用户人数"
          v-if="formThead.userCount.checked"
          min-width="110px"
        ></el-table-column>
        <el-table-column
          prop="cardCount"
          label="有卡人数"
          v-if="formThead.cardCount.checked"
          min-width="110px"
        ></el-table-column>
        <el-table-column
          prop="avgCardBalance"
          label="卡平均钱包余额(元)"
          v-if="formThead.avgCardBalance.checked"
          min-width="110px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.avgCardBalance | amountyuan }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="avgUserBalance"
          label="人均卡钱包余额(元)"
          v-if="formThead.avgUserBalance.checked"
          min-width="110px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.avgUserBalance | amountyuan }}</div>
          </template>
        </el-table-column>
          <el-table-column
          prop="sumCardBalance"
          label="卡钱包总余额(元)"
          v-if="formThead.sumCardBalance.checked"
          min-width="110px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.sumCardBalance | amountyuan }}</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      filename: '单位余额统计报表',
      departmentoptions: [],
      departmentGuid: [],
      // userName: "",
      // cardNumber: "",
      // userNumber: "",
      elform: {},
      // 表格渲染数据
      detailslist: [],
      loading: false,
      pageNum: 1,
      pageSize: 20,
      currentPage: 1,
      recordCount: 0,
      searchInfo: {},
      formThead: {
        unitName: {
          label: '单位名称',
          prop: 'unitName',
          checked: true
        },
        userCount: { label: '用户人数', prop: 'userCount', checked: true },
        cardCount: { label: '有卡人数', prop: 'cardCount', checked: true },
        avgCardBalance: {
          label: '卡平均钱包余额(元)',
          prop: 'avgCardBalance',
          checked: true
        },
        avgUserBalance: {
          label: '人均卡钱包余额(元)',
          prop: 'avgUserBalance',
          checked: true
        },
         sumCardBalance: {
          label: '卡钱包总余额(元)',
          prop: 'sumCardBalance',
          checked: true
        },
        
      },
      //导出数据
      detailslistExportlist: [],
      //汇总合计
      detailsTotal: null
    }
  },
  filters: {},
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid
      }
    }
  },
  methods: {
    // 重新渲染表格
    getHeaderDate() {
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
    },
    selectdepartment() {},
    // 查询
    async onSubmit() {
      this.pageNum = 1
      this.searchInfo = {}
      this.searchInfo.unitGuid = this.changeschoolid
      this.detailspage()
    },
    //单位分页查询
    detailspage() {
      this.loading = true
      this.$httpblob({
        url: this.$httpblob.adornUrl('/card/card-balance-statistics-unit'),
        method: 'post',
        data: this.$httpblob.adornData({
          messageContent: {
            ...this.searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.loading = false
        if (data.messageContent == null || data.messageContent.length == 0) {
          this.$message({
            message: '查询成功当前暂无数据',
            type: 'success'
          })
        }
        if (data.messageCode == 200) {
          this.detailslist = data.messageContent || []
          this.recordCount = data.messageContent.recordCount
          this.currentPage = data.messageContent.pageNum
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    async onExport(type) {
      if (this.detailslist.length == 0) {
        this.$message({
          message: '请查询数据后,在进行此操作',
          type: 'warning'
        })
        return false
      }
      await this.outexecelinit()
      if (type == 'print') {
        this.printJS()
      } else {
        this.export2Excel()
      }
    },
    // 打印
    printJS() {
      let someJSONdata = this.detailslistExportlist
      const title = '单位余额统计表'
      this.unitName = sessionStorage.getItem('unitName')
      const properties = []
      // 拿到数据formThead
      for (let key in this.formThead) {
        if (this.formThead[key].checked) {
          properties.push({
            displayName: this.formThead[key].label,
            field: this.formThead[key].prop
          })
        }
      }
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(title, this.unitName),
        printable: someJSONdata,
        properties: properties,
        type: 'json',
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem('username'),
          this.getNowTime('yy-mm-dd hh:mm:ss')
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle()
      })
    },
    //单位导出数据
    outexecelinit() {
      let _this = this
      return new Promise(function(resolve, reject) {
        _this
          .$httpblob({
            url: _this.$httpblob.adornUrl('/card/card-balance-statistics-unit'),
            method: 'post',
            data: _this.$httpblob.adornData({
              messageContent: {
                pageNum: 1,
                pageSize: _this.recordCount,
                ..._this.searchInfo
              },
              messageType: 0
            })
          })
          .then(({ data }) => {
            if (data.messageCode == 200) {
              _this.detailslistExportlist = data.messageContent || []
              for (var i = 0; i < _this.detailslistExportlist.length; i++) {
                _this.detailslistExportlist[i].avgCardBalance = _this.amountyua(
                  _this.detailslistExportlist[i].avgCardBalance
                )
                _this.detailslistExportlist[i].avgUserBalance = _this.amountyua(
                  _this.detailslistExportlist[i].avgUserBalance
                )
                 _this.detailslistExportlist[i].sumCardBalance = _this.amountyua(
                  _this.detailslistExportlist[i].sumCardBalance
                )
              }
              resolve(_this.detailslistExportlist)
            } else {
              reject(data.errorMessage)
              _this.$message.error(data.errorMessage)
            }
          })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    export2Excel() {
      const nowtime = this.getimeto()
      require.ensure([], () => {
        const multiHeader = []
        const multiHeader2 = []
        const merges = []
        const { export_json_to_excel } = require('@/excel/Export2Excel')
        // tHeaderarr.push('单位名称')

        let tHeader = []
        let filterVal = []
        for (let key in this.formThead) {
          if (this.formThead[key].checked) {
            tHeader.push(this.formThead[key].label)
            filterVal.push(this.formThead[key].prop)
          }
        }

        const list = this.detailslistExportlist
        const data = this.formatJson(filterVal, list)
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime
        })
      })
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.detailspage()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.detailspage()
    }
  }
}
</script>

<style lang="scss" scoped>
.swipe_details {
  padding: 10px;
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }

  .el-table__row .el-table__row--level-1 {
    background-color: #e5e9f2;
  }
  /deep/.el-form.el-form--inline {
    /deep/.el-form-item.el-form-item--mini {
      margin-bottom: 5px;
    }
  }
  .page {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>